'use strict'

import formidable from 'formidable'
import path from 'path'
import data from '../data/nameLstData';
import fs from 'fs';
import open from 'open';
import cheerio from 'cheerio'
const nameList = require("../data/nameLstData");
let dest_path = "E:\\2019html\\落地页\\"
export default app => {
    app.post('/loadMoban', (req, res) => {
        try {
            var html = fs.readFileSync(path.resolve(__dirname, '../public/html/'+req.body.moban+'/标准模板/'+req.body.id+''+req.body.number+'.html'))
            var $ = cheerio.load(html);
            var wrap1 = $('.wrap1').html();
           // console.log(wrap1);
            res.send({
                status: 0,
                type: 'POST_LOADMOBAN_SUCCESS',
                wrap1: wrap1
            })
        }catch (err) {
            res.send({
                status: 0,
                type: 'POST_LOADMOBAN_FAILED',
                message: '获取模板失败'
            })
        }
    })
    app.post('/addImg', async (req, res, next) => {
        try {
            const img_name = await getPath(req, res);
            res.send({
                status: 1,
                img_name
            })
        } catch (err) {
            console.log(err)
            res.send({
                status: 0,
                type: 'ERROR_UPLOAD_IMG',
                message: '上传图片失败'
            })
        }
    })
    app.get('/getNameList', (req, res, next) => {
        try {
            //fs.readdir(config.landingpageHTMLDir, function (err, data) {
            res.send({
                status: 1,
                type: 'GET_NAMELIST',
                data: nameList
            })
            //})
        } catch (err) {
            res.send({
                status: 0,
                type: 'GET_NAMELIST_ERROR'
            })
        }

    })

    app.post('/moban', async (req, res, next) => {
        try {
            var txt = req.body.txt;
            var id = req.body.moban;
            var number = req.body.number;
            var moban = ''
            for (let j = 0, l = data.length; j < l; j++) {
                if (data[j].id == id) {
                    moban = data[j].text;
                }
            }
    
            let dir = path.join(__dirname, "../public/html/" + moban + "/标准模板")
            await getStat(dir)
            let f = path.join(__dirname, "../public/html/" + moban + "/标准模板/" + id + number + ".html")

            var reg = new RegExp(/\<title\>([\s\S]*)\<\/title\>/, "g");
            txt = txt.replace(reg, "<title>" + moban + number + "</title>");
            fs.writeFile(f, txt, function (err) {
                if (err) {
                    console.log("err=>", err)
                }
            });
            //open('http://localhost:8003/html/' + moban + "/标准模板/" + moban + number + ".html", 'chrome');
            if(moban == '测试') {
                res.send({
                    status: 1,
                    type: 'POST_MOBAN_SUCCESS'
                })
                return
            }
            await getStat(path.resolve(dest_path, moban + "/标准模板"))
            let dest_f = path.resolve(dest_path, moban + "/标准模板/" + id + number + ".html")
            var reg = new RegExp('http://localhost:8082/html/'+moban, 'g');
            txt = txt.replace(reg, '//tgimg.xinkuai.com/upload/image/2019/'+id);
            fs.writeFile(dest_f, txt, (err) => {
                if (err) {
                    console.log(err)
                }
            })
            //打开最终生成的落地页
           // open('http://localhost:8006/' + moban + "/标准模板/" + id + number + ".html", 'chrome');

            res.send({
                status: 1,
                type: 'POST_MOBAN_SUCCESS'
            })
        } catch (err) {
            console.log(err)
            res.send({
                msg: err,
                status: 0,
                type: 'POST_MOBAN_ERROR'
            })
        }
    })
}

function dirExist(dir) {
    return new Promise((resolve, reject) => {
        fs.stat(dir, (err, stats) => {
            if (err) {
                resolve(false);
            } else {
                resolve(stats);
            }
        })
    })
}

function mkdir(dir) {
    return new Promise((resolve, reject) => {
        fs.mkdir(dir, err => {
            if (err) {
                resolve(false);
            } else {
                resolve(true);
            }
        })
    })
}

async function getStat(dir) {
    let dirStats = await dirExist(dir);
    if (!dirStats) {
        let fatherDirStats = await getStat(path.parse(dir).dir);
        let makeDirStatus;
        if (fatherDirStats) {
            makeDirStatus = await mkdir(dir);
            return makeDirStatus
        }
    } else {
        return true
    }
}

async function getPath(req, res) {
    return new Promise((resolve, reject) => {
        const form = formidable.IncomingForm();
        form.uploadDir = './public/html';
        form.parse(req, async (err, fields, files) => {
            let picName = Math.ceil(Math.random() * 10000);
            let extname = path.extname(files.file.name);
            let fullname = picName + extname;
            let moban = fields.moban;
            if (['.jpg', '.jpeg', '.png', '.gif'].includes(extname)) {
                let picpath = './public/html/' + moban + "/" + fields.number + "/" + fullname
                try {
                    let dir = path.join(__dirname, "../public/html/" + moban + "/" + fields.number)
                    await getStat(dir)
                    fs.renameSync(files.file.path, picpath);
                    await getStat(path.join(dest_path, moban + "/" + fields.number))
                    fs.copyFileSync(picpath, path.join(dest_path, moban + "/" + fields.number + "/" + fullname))
                    resolve(fullname)
                } catch (err) {
                    console.log("保存图片失败", err);
                    if (fs.existsSync(picpath)) {
                        fs.unlinkSync(picpath);
                    } else {
                        fs.unlinkSync(files.file.path);
                    }
                }
            } else {
                fs.unlinkSync(files.file.path);
                res.send({
                    status: 0,
                    type: 'ERROR_EXTNAME',
                    message: '文件格式错误'
                })
                reject('上传失败');
                return
            }
        })
    })
}

